import tkinter as tk
from tkinter import filedialog, messagebox
from pypdf import PdfReader, PdfWriter
import os

def split_pdf(input_pdf_path, output_folder):
    # 检查输出文件夹是否存在，如果不存在则创建
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    # 打开输入的 PDF 文件
    with open(input_pdf_path, 'rb') as file:
        # 创建 PDF 读取器对象
        reader = PdfReader(file)
        num_pages = len(reader.pages)

        # 遍历每一页
        for page_num in range(num_pages):
            # 创建 PDF 写入器对象
            writer = PdfWriter()
            # 将当前页添加到写入器中
            writer.add_page(reader.pages[page_num])

            # 生成输出文件的路径
            output_file_path = os.path.join(output_folder, f'page_{page_num + 1}.pdf')

            # 将当前页写入到输出文件中
            with open(output_file_path, 'wb') as output_file:
                writer.write(output_file)

            print(f'Page {page_num + 1} saved as {output_file_path}')

def select_pdf():
    file_path = filedialog.askopenfilename(filetypes=[("PDF files", "*.pdf")])
    if file_path:
        pdf_path.set(file_path)
        # 设置默认输出目录为输入文件所在目录下的output文件夹
        default_output = os.path.join(os.path.dirname(file_path), "output")
        output_path.set(default_output)

def start_split():
    input_pdf = pdf_path.get()
    if not input_pdf:
        messagebox.showwarning("警告", "请先选择PDF文件")
        return
    
    # 获取输出目录，如果用户没有选择则使用默认值
    output_folder = filedialog.askdirectory(initialdir=output_path.get())
    if not output_folder:
        output_folder = output_path.get()
    
    # 添加确认提示
    confirm = messagebox.askyesno("确认", f"您选择的输出目录是：\n{output_folder}\n\n是否确认？")
    if confirm:
        try:
            split_pdf(input_pdf, output_folder)
            messagebox.showinfo("成功", "PDF拆分完成！")
        except Exception as e:
            messagebox.showerror("错误", f"拆分失败: {str(e)}")
    else:
        messagebox.showinfo("信息", "操作已取消")

# 创建主窗口
root = tk.Tk()
root.title("PDF拆分工具-琪睿科技")

# 文件路径变量
pdf_path = tk.StringVar()
output_path = tk.StringVar()  # 新增输出路径变量

# 创建界面组件
tk.Label(root, text="选择PDF文件:").grid(row=0, column=0, padx=5, pady=5)
tk.Entry(root, textvariable=pdf_path, width=40).grid(row=0, column=1, padx=5, pady=5)
tk.Button(root, text="浏览", command=select_pdf).grid(row=0, column=2, padx=5, pady=5)

tk.Button(root, text="开始拆分", command=start_split).grid(row=1, column=1, padx=5, pady=10)

# 运行主循环
root.mainloop()